package net.joey.httpclient.youku.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class VideoUtils {

	public static String getServiceName(String oriUrl) {
		for (Map.Entry<Pattern, String> e : Constants.videoUrlPatternMap
				.entrySet()) {
			Pattern p = e.getKey();
			Matcher m = p.matcher(oriUrl);
			if (m.find()) {
				return e.getValue();
			}
		}
		return null;
	}

	public static String getUrlStringContent(String oriUrl,String encoding) {
		// try {
		// HttpClient httpclient = new DefaultHttpClient();
		// HttpGet httpget = new HttpGet(oriUrl);
		// HttpResponse response;
		// response = httpclient.execute(httpget);
		//
		// HttpEntity entity = response.getEntity();
		// if (entity != null) {
		// String s = EntityUtils.toString(entity, "UTF-8");
		// return s;
		// }
		// } catch (ClientProtocolException e) {
		// e.printStackTrace();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// return null;
		HttpClient client = new HttpClient();
		GetMethod get = new GetMethod(oriUrl);
		String result = null;
		StringBuffer resultBuffer = new StringBuffer();
		try {
			client.executeMethod(get);
			// 在目标页面情况未知的条件下，不推荐使用getResponseBodyAsString()方法
			// String strGetResponseBody = post.getResponseBodyAsString();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					get.getResponseBodyAsStream(), get.getResponseCharSet()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				resultBuffer.append(inputLine);
				resultBuffer.append("\n");
			}
			in.close();
			result = resultBuffer.toString();
			result = VideoUtils.converterStringCode(
					resultBuffer.toString(), get.getResponseCharSet(), null == encoding ? "UTF-8":encoding);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		return null;
	}

	public static JSONObject getUrlJsonContent(String oriUrl,String encoding) {
		String c = getUrlStringContent(oriUrl,encoding);
		System.out.println(c);
		try {
			if (null != c) {
				JSONObject json = JSONObject.fromObject(c);
				return json;
			}
		} catch (Exception e) {

		}
		return null;
	}

	private static String converterStringCode(String source, String srcEncode,
			String destEncode) {
		if (source != null) {
			try {
				return new String(source.getBytes(srcEncode), destEncode);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
